// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
var PizZip = require('pizzip');
var Docxtemplater = require('docxtemplater');
var fs = require('fs');
var path = require('path');

// 云函数入口函数
exports.main = async(event, context) => {
  const wxContext = cloud.getWXContext()
  var content = fs
    .readFileSync(path.resolve(__dirname, 'template.docx'), 'binary');
  var zip = new PizZip(content);
  var doc;
  try {
    doc = new Docxtemplater(zip);
  } catch (error) {
    // Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
    errorHandler(error);
  }

  //set the templateVariables
  doc.setData({
    teamName: 'John',
    matchItem: 'Doe',
  });

  try {
    // render the document (replace all occurences of {first_name} by John, {last_name} by Doe, ...)
    doc.render()
  } catch (error) {
    // Catch rendering errors (errors relating to the rendering of the template : angularParser throws an error)
    //errorHandler(error);
  }

  var buffer = doc.getZip()
    .generate({
      type: 'nodebuffer'
    });

    return  await  cloud.uploadFile({
    cloudPath: "doc.docx",
    fileContent: buffer, //excel二进制文件
  })
}